<?php


namespace app\admin\controller\other;


use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Db;

class Hhy extends Backend
{

    protected $noNeedRight=['*'];

    public function index(){

        return $this->fetch();
    }


    public function fileup(){
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = app()->getRootPath().DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx','txt'])) {
            $this->error(__('Unknown data format'));
        }
        $type = pathinfo($filePath);
        $type = strtolower($type["extension"]);
        $types = "";

        //txt 文档一行一个手机号！！！
        if ($type=='txt'){
            $str=$this->getTxtcontent($filePath);
            if ($str){
                $ar=explode(",",$str);
                $num=count($ar);
                $this->success('上传成功','',['num'=>$num,'phone'=>$str]);
            }else{
                $this->error('读取内容失败','');
            }
        }
        if ($type == 'xlsx') {
            $types = 'Xlsx';
        } elseif ($type == 'xls') {
            $types = 'Xls';
        }

        try {
            $objReader = IOFactory::createReader($types);
            $PHPExcel = $objReader->load($filePath);
            $currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表

            $highestColumnIndex = Coordinate::columnIndexFromString("C");//总列数
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $dataList = [];  //声明数组

            /**从第三行开始输出*/
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                /**从第A列开始输出*/
                for ($col = 1; $col < $highestColumnIndex; $col++) {
                    if ($col)
                        $dataList[] = $currentSheet->getCellByColumnAndRow($col, $currentRow)->getValue();
                }
            }
            writeLog($dataList,'test');
            foreach ($dataList as $k=>$v){
                //匹配全是数字
                $prep=preg_match('/^([1-9][0-9]*){1,18}$/',$v);
                if (empty($v) || !$prep){
                    unset($dataList[$k]);
                }
            }
            if (empty($dataList)){
                $this->error('没有获取到手机号');
            }
            writeLog($dataList,'test');
            $phones=implode(",",$dataList);
            $num=count($dataList);
            //用完就删除 文件
            @unlink($filePath);
            $this->success('上传成功','',['num'=>$num,'phone'=>$phones]);

        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

    }

    
    /**
     * @param $txtfile
     * @return string
     * 逐行读取TXT文件
     */
    protected function getTxtcontent($txtfile){
        $file = @fopen($txtfile,'r');
        $content = array();
        if(!$file){
            return false;
        }else{
            $i = 0;
            while (!feof($file)){
                $content[$i] = mb_convert_encoding(fgets($file),"UTF-8","GBK,ASCII,ANSI,UTF-8");
                $i++ ;
            }
            fclose($file);
            $content = $this->array_remove_empty($content); //数组去空
        }
        @unlink($txtfile);
        $str=@implode(",",$content);
        return $str;
    }


    /**
     * 方法库-数组去除空值
     * @param string $num  数值
     * @return array
     */
    protected function array_remove_empty(&$arr, $trim = true) {
        if (!is_array($arr)) return [];
        foreach($arr as $key => $value){
            if (is_array($value)) {
                self::array_remove_empty($arr[$key]);
            } else {
                $value = ($trim == true) ? trim($value) : $value;
                if (empty($value) || $value=="") {
                    unset($arr[$key]);
                } else {
                    $arr[$key] = $value;
                }
            }
        }
        return $arr;
    }



    public function checkht_status(){
        $id=$this->request->post("id",0);
        Db::name('admin')->where("id",$id)->update(['checkht_status'=>'1']);
        $this->success(__("Operation completed"));
    }


}